import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp

from models.Messages import *
from models.Topics import *
from models.Groups import *
from models.Users import *
from models.Audit import *
from models.Authentication import *
from decorators import *
import logging


"""------------------------------------------------------------------------
ViewGroups
------------------------------------------------------------------------"""
# @CheckUserCreated
class ViewGroups(webapp.RequestHandler):
    """
    Class is responsible for displaying the list of groups to the user. 
    Performs the necessary database queries to extract the groups from 
    the db and passes them to the ViewGroups template.
    """
    def get(self):        
        """ Responds to HTTP Get Request to /group Renders the template
        and passes in hash containing groups and number of internal topics"""

        # check to ensure that the user is loggedin before allowing them 
        # to access the page
        ourUser = get_current_user(request=self.request)
        logging.info(ourUser)
        
        if not ourUser:
          return self.redirect("/login")
        
        
        welcome = False
        moderator = ourUser.moderator
        super_user = ourUser.super_user
        
        # if it is the users first time set up to prompt for customization.
        if(ourUser.firstTime):
            welcome = True
            ourUser.firstTime = False
            ourUser.put()
        
        # fetch the groups that our users are a member of
        if len(ourUser.groups) > 0:
          logging.info(ourUser.groups)
          groups = Group.get_by_id(ourUser.groups)
          #groups.filter('key.id IN ', ourUser.groups)
        else:
          groups = []
        
        logging.info(groups)
        groupsWithCount = []
        
        # fetch the number of topics inside every group
        for group in groups:
            if group == None:
              continue
            topics = Topic.all()
            topics.filter("group_id =",group.key().id())
            count = topics.count()
            groupsWithCount.append({"group":group,"count":count})

        template_values = {"groups":groupsWithCount,"welcome":welcome,"user":ourUser, "moderator":moderator, "super_user":super_user}
        
        # getting the user agent style of the user
        user_agent = self.request.headers["User-Agent"]
        
        # redirect the user to the mobile template instead of 
        # regular template
        if user_agent.find("Mobile") >= 0:
          logging.info("You should redirect to the mobile site")
          path = os.path.join(os.path.dirname(__file__), "../templates/mobileMaster.html")
          self.response.out.write(template.render(path, template_values))
        # If we are in the standard browser then just render the normal one.
        else:
          path= os.path.join(os.path.dirname(__file__), "../templates/ViewGroups.html")
          self.response.out.write(template.render(path, template_values))

"""------------------------------------------------------------------------
NewGroup
------------------------------------------------------------------------"""
class NewGroup(webapp.RequestHandler):
    """Responsible for adding new groups. Will Render the new group form
    and also create the new groups when posted back. """
    def get(self):
        # check to ensure that the user is loggedin before allowing them 
        # to access the page
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        
        if not ourUser.super_user:
          return self.redirect("/group")
        
        
        path = os.path.join(os.path.dirname(__file__),"../templates/NewGroup.html")
        self.response.out.write(template.render(path,{}))

    def post(self):
        """ Respond to post back of new group form. Creates the new group
        object in the db and also addes new users to the group if specified.
        """
        
        # check to ensure that the user is loggedin before allowing them 
        # to access the page
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        #fetch the current user who will be the author
        
        currUser = get_current_user(self.request)
        
        # extract the form values
        requestTitle = self.request.get('title')
        member_list = self.request.get("member_list")
        newGroup = Group(title=requestTitle)
                
        # add the author to the moderators list.
        newGroup.moderators.append(currUser.email)
        newGroup.author = currUser.key().id()
        newGroup.put()
        
        
        # add the newly created group to the current users groups list
        currUser.groups.append(int(newGroup.key().id()))
        logging.info(newGroup.key().id())
        logging.info(currUser.groups)
        currUser.put()
        
        # add the users from the group user list
        email_list = self.request.get("group_input")
        email_list = email_list.split(",")
        
        # attempt to fetch the user object for the list of email addresses 
        # supplied by the super_user
        for email in email_list:
          query = User.all()
          query.filter("email = ", email)
          user = query.get()
          
          # if a user with the desired email is found then add them to 
          # group
          if user:
            user.groups.append(newGroup.key().id())
            user.put()
            logging.info(user.groups)
          
        audit = Audit(
            ip = self.request.remote_addr,
            action = "New Group",
            date = newGroup.date_created,
            userID = currUser.key().id(),
            objectID = newGroup.key().id() 
        )
        audit.setGroup()
        audit.put()
        
        self.redirect('/group/'+ str(newGroup.key().id()))



"""------------------------------------------------------------------------
DeleteGroup
------------------------------------------------------------------------"""
class DeleteGroup(webapp.RequestHandler):
    """Class is responsible for handling request to /deletegroup/:id
    Will only respond to HTTP GET request."""
    def get(self,groupID):
        """ Perform the delete action in response to GET request"""
        
        # check to ensure that the user is loggedin before allowing them 
        # to access the page
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        
        # get the group object for the supplied id.
        group = Group.get_by_id(int(groupID))
        
        currUser = get_current_user(self.request)
        
        audit = Audit(
            ip = self.request.remote_addr,
            action = "Delete Group",
            date = group.date_created,
            userID = currUser.key().id(),
            objectID = group.key().id() 
        )
        audit.setGroup()
        audit.put()
        logging.info(currUser.groups)
        logging.info(groupID)
        
        # remove the group from the users list and then delete it from the db 
        currUser.groups.remove(long(groupID))
        group.delete()
        # currUser.groups.remove(None)
        logging.info(currUser.groups)
        self.redirect('/group')
        

"""------------------------------------------------------------------------
ModifyGroup
------------------------------------------------------------------------"""
class ModifyGroup(webapp.RequestHandler):
    """Class is responsible for handling request to /modifygroup/:id"""
  
    def get(self,groupID):
        """Respond to GET request by rendering the modify group template
        will present the user with a form that allows them to make changes"""
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        group = Group.get_by_id(int(groupID))

        template_values = {"group":group}
        path = os.path.join(os.path.dirname(__file__),"../templates/ModifyGroup.html")
        self.response.out.write(template.render(path,template_values))
        
    def post(self,groupID):
        """Respond to POST request by making the changed in the db to the 
        url argument group"""
        
        # check to ensure that the user is loggedin before allowing them 
        # to access the page
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        group = Group.get_by_id(int(groupID))
        
        
        audit = Audit(
            ip = self.request.remote_addr,
            action = "Modify Group (Changed name to: "+self.request.get('groupTitle')+ ")",
            date = group.date_created,
            userID = ourUser.key().id(),
            objectID = group.key().id() 
        )
        
        audit.setGroup()
        audit.put()


        group.title = self.request.get('groupTitle')
        group.put()
        self.redirect('/group/'+str(group.key().id()))
